package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        System.out.println(password);

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);  // employeeDTO -> employee
        //设置停售
        employee.setStatus(StatusConstant.DISABLE);
        //密码md5加密后存储
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
       /* employee.setCreateTime(LocalDateTime.now());  // 创建时间
        employee.setUpdateTime(LocalDateTime.now());  // 更新时间
        //设置当前创建人id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        employeeMapper.insert(employee);
        //清理当前线程的id
        BaseContext.removeCurrentId();
    }

    /*
     * 员工信息分页查询
     * @param employeePageQueryDTO
     * @return
     * */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        //封装分页结果
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }


    /*
     * 启用禁用员工账号
     * @param status
     * @param id
     * */
    @Override
    public void startOrStop(Integer status, Long id) {
        //为了提高sql语句的复用性, 封装成update方法
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        //修改员工
        employeeMapper.updateEmp(employee);

    }

    /*
     * 根据id查询员工信息
     * @param id
     * @return
     * */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        //对密码进行隐藏
        employee.setPassword("****");
        return employee;
    }

    /*
     * 编辑员工信息
     * @param employeeDTO
     * */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //将dto对象转为entity对象
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        //设置停售
        employee.setStatus(StatusConstant.DISABLE);
        /*//设置修改时间和修改人
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        employeeMapper.updateEmp(employee);
        //清理当前线程的id
        BaseContext.removeCurrentId();
    }

    /**
     * 编辑员工密码
     * @param passwordEditDTO
     */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        //先校验旧密码 加密验证
        String oldPasswoerd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        //查询旧密码
        Employee employee = employeeMapper.getById(passwordEditDTO.getEmpId());
        if (!oldPasswoerd.equals(employee.getPassword())) {
            //密码错误  抛出密码错误异常 并被全局异常处理类处理
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //新密码加密并设置
        String newPasswoerd = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        employee.setPassword(newPasswoerd);
        /*//更新当前时间和操作人id
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());*/
        //更新员工
        employeeMapper.updateEmp(employee);
    }


}
